<template>
  <div class="page">
    <div class="tools">
      <div v-for="(item, index) in tools" :key="index">
        <div class="title">{{ item.group }}</div>
        <div class="buttons">
          <a
            v-for="(btn, i) in item.children"
            :key="i"
            :title="btn.name"
            :draggable="btn.data"
            @dragstart="onDrag($event, btn)"
          >
            <i :class="`iconfont ${btn.icon}`"></i>
          </a>
        </div>
      </div>
    </div>
    <el-container>
      <!-- <el-header> -->
      <Head @ee="changshow"></Head>
      <!-- </el-header> -->

      <el-main>
        <el-row>
          <el-col :span="24">
            <!-- <el-button type="text" @click="dialogVisible = true"
              >点击打开 Dialog</el-button
            > -->

            <div
              id="topology-canvas"
              class="full"
              :style="backgroundDiv"
              @contextmenu="onContextMenu($event)"
            ></div>
          </el-col>
        </el-row>
      </el-main>
      <el-footer> </el-footer>
    </el-container>

    <!-- <div  
      id="topology-canvas"
      class="full"
      @contextmenu="onContextMenu($event)"
    ></div> -->
    <div class="props">
      <CanvasProps
        :props.sync="props"
        :inputname="filenamefromson"
        @change="onUpdateProps"
        @filenamechange="changename"
      ></CanvasProps>
      <!-- v-bind:val_1="3456" -->
    </div>
    <div class="context-menu" v-if="contextmenu.left" :style="this.contextmenu">
      <CanvasContextMenu
        :canvas="canvas"
        :props.sync="props"
      ></CanvasContextMenu>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>新增设备类型(可不填)：</span>
      <el-row>
        <el-col :span="20">
          <el-input type="text" v-model="value2" autocomplete="off"></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addnewtype">确定</el-button>
        </el-col>
      </el-row>
      <span>新增iconFont图标地址：</span>
      <el-input type="text" v-model="value3" autocomplete="off"></el-input>
      <!-- <el-divider></el-divider> -->
      <span>控件设备类型：</span>
      <el-select v-model="value" placeholder="请选择将要添加的目录">
        <el-option
          v-for="(item, index) in tools"
          :key="index"
          :label="item.group"
          :value="index"
        >
        </el-option>
      </el-select>
      <el-form
        :model="newchildren"
        status-icon
        ref="newchildren"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="新控件名字:" class="redItem">
          <el-input
            type="text"
            v-model="newchildren.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件图标:">
          <el-input
            type="text"
            v-model="newchildren.icon"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件ID:">
          <el-input
            type="text"
            v-model="newchildren.data.id"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件文本:">
          <el-input
            type="text"
            v-model="newchildren.data.text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件长度:">
          <el-input
            type="text"
            v-model="newchildren.data.rect.width"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件宽度:">
          <el-input
            type="text"
            v-model="newchildren.data.rect.height"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新控件类型:">
          <el-input
            type="text"
            v-model="newchildren.data.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="画布显示图标:">
          <el-input
            type="text"
            v-model="newchildren.data.icon"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图标字体:">
          <el-input
            type="text"
            v-model="newchildren.data.iconFamily"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="填充颜色:">
          <el-input
            type="text"
            v-model="newchildren.data.iconColor"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="showinfo">提交</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Topology } from 'topology-core'
import { Node } from 'topology-core/models/node'
import { Line } from 'topology-core/models/line'
import * as FileSaver from 'file-saver'

import { Tools, canvasRegister } from '~/services/canvas'

import CanvasProps from '~/components/CanvasProps'
import CanvasContextMenu from '~/components/CanvasContextMenu'
import Head from '~/components/head'
import Index from '~/components/index'
import Cookies from 'js-cookie' //npm install js-cookie --save yarn add js-cookie

export default {
  data() {
    return {
      tools: Tools,
      dialogVisible: false,
      selectRow: [],
      selectData: [],
      backgroundDiv: {
        // backgroundImage:
        //   'url(' + require('../assets/images/background0.jpg') + ')',
        // backgroundColor: '#B7F1F2',
        // backgroundRepeat: 'no-repeat',
        // backgroundSize: '100% 100%'
      },
      value: '',
      value2: '',
      value3: '',
      id: '',
      newtype: {
        group: '',
        children: [
          {
            name: '',
            icon: '',
            data: {
              id: '',
              text: '',
              rect: {
                width: null,
                height: null
              },
              paddingLeft: 10,
              paddingRight: 10,
              paddingTop: 10,
              paddingBottom: 10,
              name: '',
              icon: '',
              iconFamily: '',
              iconColor: ''
            }
          }
        ]
      },
      newchildren: {
        name: '',
        icon: '',
        data: {
          id: '',
          text: '',
          rect: {
            width: null,
            height: null
          },
          paddingLeft: null,
          paddingRight: null,
          paddingTop: null,
          paddingBottom: null,
          name: '',
          icon: '',
          iconFamily: '',
          iconColor: ''
        }
      },

      // tools: [
      //   {
      //     group: '',
      //     children: [
      //       {
      //         name: '',
      //         icon: '',
      //         data: {
      //           id: '',
      //           text: '',
      //           rect: {
      //             width: null,
      //             height: null
      //           },
      //           paddingLeft: 10,
      //           paddingRight: 10,
      //           paddingTop: 10,
      //           paddingBottom: 10,
      //           name: '',
      //           icon: '',
      //           iconFamily: '',
      //           iconColor: ''
      //         }
      //       }
      //     ]
      //   }
      // ],
      filenamefromson: '空白文件',
      filenamefromson2: '',
      canvas: {},
      canvasOptions: {
        rotateCursor: '/img/rotate.cur'
      },
      props: {
        a: null,
        node: null,
        line: null,
        nodes: null,
        multi: false,
        locked: false
      },
      contextmenu: {
        left: null,
        top: null,
        bottom: null
      }
    }
  },
  components: {
    CanvasProps,
    CanvasContextMenu,
    Head,
    Index
  },
  computed: {
    event() {
      return this.$store.state.event.event
    }
  },
  watch: {
    event(curVal) {
      if (this['handle_' + curVal.name]) {
        this['handle_' + curVal.name](curVal.data)
      }
    },
    $route(val) {
      this.open()
    }
  },
  created() {
    canvasRegister()
    //控制鼠标右键点击的面板当点击空白处时消失
    if (process.client) {
      document.onclick = event => {
        this.contextmenu = {
          left: null,
          top: null,
          bottom: null
        }
      }
    }
  },
  mounted() {
    this.canvasOptions.on = this.onMessage
    this.canvas = new Topology('topology-canvas', this.canvasOptions)
    this.open()
    // this.tools = Tools
    // let lastname = window.localStorage.getItem('data')
    // let newstr = JSON.parse(lastname)

    // this.tools = newstr
    // //加载以前的iconFOnt地址
    // var head = document.getElementsByTagName('head')
    // var new_link = document.createElement('link')
    // new_link.type = 'text/css'
    // new_link.href = window.localStorage.getItem('iconaddress')
    // new_link.rel = 'stylesheet' //还要加上这句才行
    // head[0].appendChild(new_link)
    // console.log(window.localStorage.getItem('iconaddress'))
  },
  methods: {
    changename(data) {
      this.filenamefromson = data
      console.log(this.filenamefromson)
    },
    changshow() {
      console.log('执行了。。。。')
      this.dialogVisible = true
    },
    addnewtype() {
      this.newtype.group = this.value2
      this.tools.push(this.newtype)
    },
    addlink() {
      //向网页添加<link>链接
      var head = document.getElementsByTagName('head')
      var new_link = document.createElement('link')
      new_link.type = 'text/css'
      new_link.href = this.value3
      new_link.rel = 'stylesheet' //还要加上这句才行
      head[0].appendChild(new_link)
      window.localStorage.setItem('iconaddress', new_link.href)
    },
    showinfo() {
      this.addlink()
      // this.tools[0].children[i].name = '发电机2'
      // this.tools[0].children[i].icon = 'icon-zbfadianji'
      // this.tools[0].children[i].data.id = '发电机2'
      // this.tools[0].children[i].data.text = '发电机2'
      // this.tools[0].children[i].data.rect.width = 120
      // this.tools[0].children[i].data.rect.height = 120
      // this.tools[0].children[i].data.paddingLeft = 10
      // this.tools[0].children[i].data.paddingRight = 10
      // this.tools[0].children[i].data.paddingTop = 10
      // this.tools[0].children[i].data.paddingBottom = 10
      // this.tools[0].children[i].data.name = 'image'
      // this.tools[0].children[i].data.icon = '\ue102'
      // this.tools[0].children[i].data.iconFamily = 'iconfont'
      // this.tools[0].children[i].data.iconColor = '#1CF0F2'
      // this.newchildren.name = '发电机2'
      // this.newchildren.icon = 'icon-zbfadianji'
      // this.newchildren.data.id = '发电机2'
      // this.newchildren.data.text = '发电机2'
      // this.newchildren.data.rect.width = 120
      // this.newchildren.data.rect.height = 120
      // this.newchildren.data.paddingLeft = 10
      // this.newchildren.data.paddingRight = 10
      // this.newchildren.data.paddingTop = 10
      // this.newchildren.data.paddingBottom = 10
      // this.newchildren.data.name = 'image'
      // this.newchildren.data.icon = newicon
      let newicon = this.newchildren.data.icon
      //执行newicon中的js代码，如果不用这个方法，那么变量中的js形式的内容只能以字符串的形式输出
      this.newchildren.data.icon = eval("'" + newicon + "'")
      // String.fromCharCode(newicon)

      // let str = newicon
      // str = eval("'" + str + "'")
      // console.log(str)
      // str = unescape(str.replace(/\u/g, '%u'))
      // console.log(str)

      let j = this.value
      this.tools[j].children.push(this.newchildren)
      let str = JSON.stringify(this.tools)
      console.log(this.tools)
      console.log(str)
      //cookies大小有限制，无法存取大量的数据，只能用Localstorage来将数据存储到本地。。
      window.localStorage.setItem('data', str)

      // Cookies.set('data', 'eee')
      // Cookies.remove('alldata')
      // let newstr = Cookies.getJSON('data')  localStorage.removeItem("key");
      let lastname = window.localStorage.getItem('data')
      let newstr = JSON.parse(lastname)

      console.log(lastname)
      console.log(newstr)
      this.tools = newstr
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },

    rowClass({ row, rowIndex }) {
      // if (this.selectRow.includes(rowIndex)) {
      //   return { 'background-color': 'rgba(185,221,249,0.75)' }
      // }
      // console.log(row, rowIndex)
    },
    async open() {
      if (!this.$route.query.id) {
        return
      }
      const data = await this.$axios.$get(
        '/api/topology/' + this.$route.query.id
      )
      if (data && data.id) {
        this.canvas.open(data.data)
      }
    },

    onDrag(event, node) {
      // node.data.text="发电机"
      console.log(JSON.stringify(node.data.id))
      // let n = node.data.text
      // node.data.text = n + new Date().getTime()
      let n = node.data.id
      node.data.id = n + new Date().getTime()
      //解决拖拽元素后，火狐浏览器会弹出一个窗口的问题。
      document.body.ondrop = function(event) {
        event.preventDefault()

        event.stopPropagation()
      }
      event.dataTransfer.setData('Text', JSON.stringify(node.data))
      console.log('创建了一个数据库')
      console.log(JSON.stringify(node.data.id))
      //  node.data.text=node.data.text+new Date().getTime()
      // this.$axios.get('http://127.0.0.1:8082/add/table').then(
      //   res=>{
      //       console.log(res.data);

      //   }
      // )
      //   this.$axios({
      //     method:'post',
      //     url:'http://127.0.0.1:8082/add/table2',
      //     data:{
      //       tablename:node.data.text
      //     }
      //   }).then((res)=>{
      //     console.log(res.data);
      //   })
      this.$axios({
        method: 'get',
        params: {
          // tablename:node.data.text+new Date().getTime()
          tablename: node.data.id
        },
        url: 'http://127.0.0.1:8082/add/table2'
      }).then(res => {
        console.log(res.data)
      })
      node.data.id = n
      this.$message({
        type: 'info',
        message: '增加设备成功'
      })
    },
    creatTab() {
      alert('创建了一个对应的数据库')
    },

    onMessage(event, data) {
      switch (event) {
        //当画布中元素被选中后执行的操作
        case 'node':
          this.props = {
            node: data,
            line: null,
            multi: false,
            nodes: null,
            locked: data.locked
          }
          console.log(data.id)
          this.$axios({
            method: 'get',
            params: {
              // tablename:node.data.text+new Date().getTime()
              tablename: data.id
            },
            url: 'http://127.0.0.1:8082/add/getAll'
          }).then(res => {
            console.log(res.data)
            // this.props.value.value_1=res.data[0].speed;
            // console.log( this.props.value.value_1);
            //当选中的时候赋予属性值node
            this.props = {
              a: res.data[0].speed,
              node: data,
              line: null,
              multi: false,
              nodes: null,
              locked: data.locked
            }
          })
          break
        case 'addNode':
          this.props = {
            node: data,
            line: null,
            multi: false,
            nodes: null,
            locked: data.locked
          }

          break
        case 'line':
        case 'addLine':
          this.props = {
            node: null,
            line: data,
            multi: false,
            nodes: null,
            locked: data.locked
          }
          break
        case 'multi':
          this.props = {
            node: null,
            line: null,
            multi: true,
            nodes: data.nodes.length > 1 ? data.nodes : null,
            locked: this.getLocked(data)
          }
          break
        case 'space':
          this.props = {
            node: null,
            line: null,
            multi: false,
            nodes: null,
            locked: false
          }
          break
        case 'moveOut':
          break
        case 'moveNodes':
        case 'resizeNodes':
          if (data.length > 1) {
            this.props = {
              node: null,
              line: null,
              multi: true,
              nodes: data,
              locked: this.getLocked({ nodes: data })
            }
          } else {
            this.props = {
              node: data[0],
              line: null,
              multi: false,
              nodes: null,
              locked: false
            }
          }
          break
        case 'resize':
        case 'scale':
        case 'locked':
          if (this.canvas && this.canvas.data) {
            this.$store.commit('canvas/data', {
              scale: this.canvas.data.scale || 1,
              lineName: this.canvas.data.lineName,
              fromArrowType: this.canvas.data.fromArrowType,
              toArrowType: this.canvas.data.toArrowType,
              fromArrowlockedType: this.canvas.data.locked
            })
          }
          break
      }
    },

    getLocked(data) {
      let locked = true
      if (data.nodes && data.nodes.length) {
        for (const item of data.nodes) {
          if (!item.locked) {
            locked = false
            break
          }
        }
      }
      if (locked && data.lines) {
        for (const item of data.lines) {
          if (!item.locked) {
            locked = false
            break
          }
        }
      }

      return locked
    },
    //全局锁定解锁拓扑
    handle_getLocked() {
      console.log(this.canvas.data.locked)
      if (this.canvas.data.locked == 1) {
        this.canvas.data.locked = 0
      } else if (this.canvas.data.locked == 0) {
        this.canvas.data.locked = 1
      }
    },

    onUpdateProps(node) {
      // 如果是node属性改变，需要传入node，重新计算node相关属性值
      // 如果是line属性改变，无需传参
      this.canvas.updateProps(node)
    },

    handle_new(data) {
      this.canvas.open({ nodes: [], lines: [] })
    },

    handle_open(data) {
      this.handle_replace(data)
    },

    handle_replace(data) {
      const input = document.createElement('input')
      input.type = 'file'
      input.onchange = event => {
        const elem = event.srcElement || event.target
        if (elem.files && elem.files[0]) {
          const name = elem.files[0].name.replace('.json', '')
          console.log(name)
          this.filenamefromson = name
          console.log(1111111111111)
          console.log('filenamefromson' + this.filenamefromson)
          const reader = new FileReader()
          reader.onload = e => {
            const text = e.target.result + ''
            try {
              const data = JSON.parse(text)
              console.log(data)
              if (
                // data &&
                // Array.isArray(data.nodes) &&
                // Array.isArray(data.lines)
                data
              ) {
                console.log(data)
                this.canvas.open(data)
              }
            } catch (e) {
              return false
            }
          }
          reader.readAsText(elem.files[0])
        }
      }
      input.click()
    },
    //将拓扑图保存到数据库中
    handle_savetodatabase(data) {
      console.log(this.filenamefromson)
      if (this.filenamefromson === this.filenamefromson2) {
        //更新拓扑
        let newname = this.filenamefromson
        let toplo = this.$qs.parse({
          id: this.id,
          toponame: newname,
          data: JSON.stringify(this.canvas.data)
        })
        this.$axios({
          headers: {
            Authorization: ' ',
            'content-Type': 'application/json;charset=UTF-8'
            //  Accept: 'application/json;charset=UTF-8'
          },
          method: 'post',
          url: 'http://127.0.0.1:8082/topology/addtopology',
          data: toplo
        }).then(res => {
          this.$message.success('更新拓扑成功')
          console.log(res.data)
        })
      } else {
        //增加新拓扑
        let newname = this.filenamefromson
        let toplo = this.$qs.parse({
          toponame: newname,
          data: JSON.stringify(this.canvas.data)
        })
        this.$axios({
          headers: {
            Authorization: ' ',
            'content-Type': 'application/json;charset=UTF-8'
            //  Accept: 'application/json;charset=UTF-8'
          },
          method: 'post',
          url: 'http://127.0.0.1:8082/topology/addtopology',
          data: toplo
        }).then(res => {
          this.$message.success('增加拓扑成功')
          console.log(res.data)
        })
      }
    },

    //将保存到数据库中的拓扑图读出来
    handle_readtodatabase(data) {
      this.$axios({
        method: 'get',
        params: {
          name: this.filenamefromson
        },
        url: 'http://127.0.0.1:8082/topology/readtopology'
      }).then(res => {
        this.filenamefromson2 = res.data.toponame
        this.filenamefromson = this.filenamefromson2
        this.id = res.data.id
        let newdata = JSON.parse(res.data.data)
        this.canvas.open(newdata)
      })
    },
    handle_save(data) {
      FileSaver.saveAs(
        new Blob([JSON.stringify(this.canvas.data)], {
          type: 'text/plain;charset=utf-8'
        }),
        // `le5le.topology.json`
        // `11111.json`
        this.filenamefromson + '.json'
      )
    },

    handle_savePng(data) {
      this.canvas.saveAsImage(this.filenamefromson + '.png')
    },

    handle_saveSvg(data) {
      const ctx = new C2S(
        this.canvas.canvas.width + 200,
        this.canvas.canvas.height + 200
      )
      for (const item of this.canvas.data.nodes) {
        item.render(ctx)
      }

      for (const item of this.canvas.data.lines) {
        item.render(ctx)
      }

      let mySerializedSVG = ctx.getSerializedSvg()
      mySerializedSVG = mySerializedSVG.replace(
        '<defs/>',
        `<defs>
    <style type="text/css">
      @font-face {
        font-family: 'topology';
        src: url('http://at.alicdn.com/t/font_1331132_h688rvffmbc.ttf?t=1569311680797') format('truetype');
      }
    </style>
  </defs>`
      )

      mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x')

      const urlObject = window.URL || window
      const export_blob = new Blob([mySerializedSVG])
      const url = urlObject.createObjectURL(export_blob)

      const a = document.createElement('a')
      a.setAttribute('download', 'le5le.topology.svg')
      a.setAttribute('href', url)
      const evt = document.createEvent('MouseEvents')
      evt.initEvent('click', true, true)
      a.dispatchEvent(evt)
    },

    handle_undo(data) {
      this.canvas.undo()
    },

    handle_redo(data) {
      this.canvas.redo()
    },

    handle_copy(data) {
      this.canvas.copy()
    },

    handle_cut(data) {
      this.canvas.cut()
    },

    handle_parse(data) {
      this.canvas.paste()
    },

    handle_state(data) {
      this.canvas.data[data.key] = data.value
      this.$store.commit('canvas/data', {
        scale: this.canvas.data.scale || 1,
        lineName: this.canvas.data.lineName,
        fromArrowType: this.canvas.data.fromArrowType,
        toArrowType: this.canvas.data.toArrowType,
        fromArrowlockedType: this.canvas.data.locked
      })
    },

    onContextMenu(event) {
      event.preventDefault() //阻止默认行为
      event.stopPropagation() //阻止冒泡

      if (event.clientY + 360 < document.body.clientHeight) {
        this.contextmenu = {
          left: event.clientX + 'px',
          top: event.clientY + 'px'
        }
      } else {
        this.contextmenu = {
          left: event.clientX + 'px',
          bottom: document.body.clientHeight - event.clientY + 'px'
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
html {
  // font-size: 100px;
}
body {
  // font-size: 1.2rem;
  line-height: 2;
}
#topology-canvas {
  width: 100%;
  height: 800px;
  background-image: url(../../assets/images/新UI23.png);
  // background-repeat: no-repeat;
  background-size: 100% 100%;
}
.redItem .el-form-item__label {
  color: black;
}
.current-row > td {
  background: rgba(0, 158, 250, 0.219) !important;
}
.tabletype {
  border-radius: 20px;
}

.page {
  display: flex;
  width: 100%;
  // height: 100%;

  .tools {
    flex-shrink: 0;
    width: 17.5rem;
    background-color: #f8f8f8;
    // background-color: rgb(0, 101, 105);
    border-right: 1px solid #d9d9d9;
    overflow-y: auto;

    .title {
      color: #0d1a26;
      font-weight: 600;
      font-size: 1.2rem;
      line-height: 1;
      padding: 0.5rem 1rem;
      margin-top: 0.8rem;
      border-bottom: 1px solid #ddd;

      &:first-child {
        border-top: none;
      }
    }

    .buttons {
      padding: 1rem 0;
      a {
        display: inline-block;
        color: #314659;
        line-height: 1;
        width: 4rem;
        height: 4rem;
        text-align: center;
        text-decoration: none !important;

        .iconfont {
          font-size: 2.4rem;
        }
      }
    }
  }

  .full {
    flex: 1;
    width: initial;
    position: relative;
    overflow: auto;
    background: #fff;
    // background-image: url("+require('../assets/images/timg.jpg')")
  }

  .props {
    flex-shrink: 0;
    width: 24rem;
    padding: 1rem 0;
    background-color: #f8f8f8;
    border-left: 1px solid #d9d9d9;
    overflow-y: auto;
    position: relative;
  }

  .context-menu {
    position: fixed;
    z-index: 10;
  }
}
</style>
